package com.sxdz.controller.filter

import com.sxdz.constant.GlobalConstant
import groovy.transform.CompileStatic
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * 跨域访问设置过滤器
 *
 */
@CompileStatic
@Component
class CorsResponseFilter implements Filter {

    private Logger log = LoggerFactory.getLogger(CorsResponseFilter.class);
    private String crosHosts = GlobalConstant.getString("crosHosts");

    @Override
    void init(FilterConfig filterConfig) throws ServletException {
//        log.info("==============================CorsResponseFilter=========================init")
    }

    @Override
    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        log.info("==============================CorsResponseFilter=========================doFilter")

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String method = httpServletRequest.method;
        httpServletResponse.addHeader("Access-Control-Allow-Origin", crosHosts)
        httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true")
        httpServletResponse.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
        httpServletResponse.addHeader("P3P","CP='IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT'")
        switch (method){
            case "OPTIONS" :

                httpServletResponse.addHeader("Access-Control-Allow-Headers", "Cookie,Authorization,Range,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type")
                httpServletResponse.addHeader("Access-Control-Expose-Headers", "Accept-Ranges,Content-Encoding,Content-Length,Content-Range")

                break;
            case 'POST':
            case "PUT":
            case "DELETE":
                httpServletResponse.addHeader("Access-Control-Allow-Headers", "Cookie,Authorization,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type")
                break;
            case "GET":
                httpServletResponse.addHeader("Access-Control-Allow-Headers", "Cookie,Authorization,Range,DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
                httpServletResponse.addHeader("Access-Control-Expose-Headers", "Accept-Ranges,Content-Encoding,Content-Length,Content-Range");
                break;
            case "HEAD":
                break;
        }
        chain.doFilter(request, response);
    }

    @Override
    void destroy() {
//        log.info("==============================CorsResponseFilter=========================destroy")
    }
}
